import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:free_music_player/models/song_model.dart';
import 'package:free_music_player/providers/music_provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:free_music_player/widgets/playing_screen.dart';

class HistoryScreen extends StatefulWidget {
  const HistoryScreen({super.key});

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  List<SongModel> _historySongs = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadHistory();
  }

  Future<void> _loadHistory() async {
    try {
      final provider = Provider.of<MusicProvider>(context, listen: false);
      final historyIds = provider.history;
      List<SongModel> songs = [];

      for (int id in historyIds) {
        try {
          SongModel song = await provider.getSongDetail(id);
          songs.add(song);
        } catch (e) {
          print('获取历史歌曲详情失败: $e');
        }
      }

      setState(() {
        _historySongs = songs;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载历史记录失败: $e')),
      );
    }
  }

  void _playSong(SongModel song) {
    Provider.of<MusicProvider>(context, listen: false)
        .setPlaylistAndPlay([song], 0);

    // 导航到播放界面
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const PlayingScreen(),
      ),
    );
  }

  Future<void> _clearHistory() async {
    try {
      await Provider.of<MusicProvider>(context, listen: false).clearHistory();
      setState(() {
        _historySongs = [];
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('历史记录已清除')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('清除历史记录失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('播放历史'),
        actions: [
          IconButton(
            icon: const Icon(Icons.clear_all),
            onPressed: _clearHistory,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _historySongs.isEmpty
              ? const Center(child: Text('暂无播放历史'))
              : ListView.builder(
                  itemCount: _historySongs.length,
                  itemBuilder: (context, index) {
                    final song = _historySongs[index];
                    return ListTile(
                      leading: CachedNetworkImage(
                        imageUrl: song.album.picUrl,
                        width: 50,
                        height: 50,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => const
                            CircularProgressIndicator(),
                        errorWidget: (context, url, error) =>
                            const Icon(Icons.music_note),
                      ),
                      title: Text(song.name),
                      subtitle: Text(song.artistsName),
                      trailing: Text(song.formattedDuration),
                      onTap: () => _playSong(song),
                    );
                  },
                ),
    );
  }
}